package com.xxx.store.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxx.store.entity.Cart;
import com.xxx.store.service.CartService;
import com.xxx.store.util.JsonResult;
import com.xxx.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/carts")
public class CartController extends BaseController{
    @Autowired
    private CartService cartService;

    @RequestMapping("/addToCart")
    public JsonResult<Void> addToCart(HttpSession session,Integer pid,Integer num){
        cartService.addToCart(getUidFromSession(session),pid,num,getUsernameFromSession(session));
        return new JsonResult<>(OK);
    }

    @RequestMapping({"","/"})
    public JsonResult<PageInfo<CartVO>> getCart(@RequestParam(value = "pn",defaultValue = "1")Integer pn,HttpSession session){
        PageHelper.startPage(pn,3);
        List<CartVO> cart = cartService.getCartByUid(getUidFromSession(session));
        PageInfo<CartVO> page = new PageInfo<>(cart,2);
        return new JsonResult<>(OK,page);
    }
    @RequestMapping("/num/add/{cid}")
    public JsonResult<Integer> addNum(HttpSession session, @PathVariable("cid") Integer cid){
        Integer num = cartService.addNum(cid, getUidFromSession(session), getUsernameFromSession(session));
        return new JsonResult<>(OK,num);
    }
    @RequestMapping("/num/reduce/{cid}")
    public JsonResult<Integer> reduceNum(HttpSession session, @PathVariable("cid") Integer cid){
        Integer num = cartService.reduceNum(cid, getUidFromSession(session), getUsernameFromSession(session));
        return new JsonResult<>(OK,num);
    }
    @RequestMapping("/list")
    public JsonResult<List<CartVO>> getVOByCid(HttpSession session,Integer[] cids){
        List<CartVO> cart = cartService.getCartByCid(getUidFromSession(session),cids);
        return new JsonResult<>(OK,cart);
    }
}
